<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\App\WorkEmployee\Action\Dashboard;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\User\Contract\UserContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 员工管理- 重置分机号.
 *
 * Class MobileReset.
 * @Controller
 */
class ExtnReset extends AbstractAction
{
    const EXTN = [
        1001 => "10041",
        1002 => "10042",
        1003 => "10043",
        1004 => "10044",
        1005 => "10045",
        1006 => "10046",
        1007 => "10047",
        1008 => "10048",
        1009 => "10049",
        1010 => "10050",
        1011 => "10051",
        1012 => "10052",
        1013 => "10053",
        1014 => "10054",
        1015 => "10055",
        1016 => "10056",
        1017 => "10057",
        1018 => "10058",
        1019 => "10059",
        1020 => "10060",
        1021 => "10061",
        1022 => "10062",
        1023 => "10063",
        1024 => "10064",
        1025 => "10065",
        1026 => "10066",
        1027 => "10067",
        1028 => "10068",
        1029 => "10069",
        1030 => "10070",
        1031 => "10071",
        1032 => "10072",
    ];
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userService;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workEmployee/extnReset", methods="put")
     * @return array 返回数组
     */
    public function index()
    {
        // 参数验证
        $this->validated($this->request->all());
        // 当前登录用户
        $user = user();
        // 接收参数
        $employeeId = $this->request->input('id');
        $extn = $this->request->input('extn');

        // 验证employeeId的有效性
        $employee = $this->workEmployeeService->getWorkEmployeeById((int) $employeeId, ['id', 'log_user_id', 'corp_id']);
        if (empty($employee)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '当前员工不存在，不可操作');
        }

        $userId = $employee['logUserId'];
        if ($employee['corpId'] != $user['corpIds'][0]) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '当前员工您没有权限操作');
        }

//        // 存在相同手机号则不能修改
//        $userExtnInfo = $this->userService->getUserByPhone($extn, ['id']);
//        if (! empty($userExtnInfo) && $userExtnInfo['id'] != $userId) {
//            throw new CommonException(ErrorCode::INVALID_PARAMS, '该分机号已分配，请更换其他分机号');
//        }

        if (!isset(self::EXTN[$extn])){
            throw new CommonException(ErrorCode::INVALID_PARAMS, $extn.'改分机号未设置队列号,请联系管理员');
        }

        try {
            Db::beginTransaction();
            $this->userService->updateUserByExtn($extn, [
                'extn' => null,
                'queue' => null,
            ]);
            // 数据入库
            $this->userService->updateUserById((int) $userId, ['extn' => $extn,'queue'=>self::EXTN[$extn]]);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            throw new CommonException(ErrorCode::SERVER_ERROR, '账户分配分机号失败');
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required|min:1',
            'extn' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => '员工id 必填',
            'extn.required' => '分机号 必填',
        ];
    }
}
